<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" >
      <el-form-item label="园区" prop="area">
        <el-select v-model="queryParams.area" placeholder="请选择园区"  style="width: 240px" @change="handleQuery">
          <el-option label="全部" value="" ></el-option>
          <el-option v-for="item in dict.type.user_area" :label="item.label" :value="item.value" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="请购单号" prop="panNum" v-show="showSearch">
        <el-input
          v-model="queryParams.panNum"
          placeholder="请输入盘点单号"
          clearable
          style="width: 240px"
          @clear="handleQuery"
        />
      </el-form-item>
      <el-form-item v-show="showSearch">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-form-item>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-form>
    <el-table v-loading="loading" :data="rowList">
      <el-table-column label="编号" align="center" prop="id" min-width="80" />
      <el-table-column label="盘点单号" align="center" prop="panNum" min-width="180" />
      <el-table-column label="园区" align="center" prop="area" width="120"/>
      <el-table-column label="结账日期" align="center" prop="panTime" width="120">
      </el-table-column>
      <el-table-column label="盘点人" prop="createBy" width="120" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="{row}">
          <span>{{ parseTime(row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="approvalUser" width="180">
        <template v-slot="{row}">
          <span v-show="!row.editFlag">{{ row.approvalUser }}</span>
          <el-select v-show="row.editFlag" v-model="row.approvalUserId" placeholder="请选择审核人" clearable :style="{width: '100%'}">
            <el-option v-for="item in approvalList"  :label="item.nickName" :value="item.userId"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="approvalState" width="150">
        <template v-slot="{row}">
          <span v-if="row.approvalState==='0'">待审核</span>
          <span v-if="row.approvalState==='1'">审核中</span>
          <span v-if="row.approvalState==='2'">审核不通过</span>
          <span v-if="row.approvalState==='3'">审核通过</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" prop="updateBy" width="160" align="center"/>
      <el-table-column label="修改时间" align="center" prop="createTime" width="180">
        <template v-slot="{row}">
          <span>{{ parseTime(row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width" fixed="right">
        <template v-slot="{row}" >
          <el-button size="small" type="text" icon="CircleCheck" v-show="row.editFlag"  @click="submit(row)">保存</el-button>
          <el-button size="small" type="text" icon="CircleClose" v-show="row.editFlag" @click="cancel(row)">取消
          </el-button>
          <el-button v-if="row.approvalState==='0'"  v-show="!row.editFlag"  size="mini" type="text" icon="el-icon-check" @click="surePan(row)">提交审核</el-button>
          <el-button size="mini"  type="text" icon="el-icon-edit" @click="handleDetail(row)">明细</el-button>
          <el-button v-if="row.approvalState!=='3'"  v-show="!row.editFlag"  size="mini" type="text" icon="el-icon-delete"  @click="handleDelete(row)">删除</el-button>
          <el-button type="text"  icon="el-icon-download" size="mini" @click="rowExport(row)">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body :close-on-click-modal="false" @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="盘点月份:" prop="panTime">
          <el-date-picker  v-model="form.panTime" placeholder="请选择月份" type="month" align="right"
                           format="yyyy年MM月" value-format="yyyy-MM"  :clearable="false">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" >确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, listAll, get, add, update } from "@/api/store/plan/normal";
import { listAll as listAllVendor } from "@/api/store/vendor";
import { getDicts } from "@/api/system/dict/data";
import {
  confirmStorePan,
  deletePanInfo, getAllApprovalList,
  getPanDetail,
  getPanInfo,
  getStoreDetailList,
  panDel,
  panList, panUpdate,
  saveNewStorePan, updateStorePan
} from "@/api/store/calculate/calculate";
import {changeRule} from "@/utils/formRules";
export default {
  name: "Detail",
  dicts:['user_area'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食材表格数据
      rowList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isEdit:true,
      // 日期范围
      dateRange: [],
      vendorOptions: [],
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        panNum:'',
        area:'',
      },
      // 表单参数
      form: {
        panTime:'',
      },
      // 表单校验
      rules: {
        panTime:changeRule('请选择盘点月份')
      },
      approvalList:[]
    };
  },
  created() {
    this.queryParams.area=this.$store.state.user.userInfo.area || ''
    this.getList();
    this.getAllApprovalList()
  },
  methods: {
    //获取审批人
    getAllApprovalList(){
      getAllApprovalList().then(res=>{
        this.approvalList=res.data
      })
    },
    /** 查询列表 */
    getList() {
      panList(this.queryParams).then(res => {
        res.rows.map(item=>{
          item.editFlag=false
        })
        this.rowList=res.rows
      })
    },
    //盘点数量变化
    realAmountChange(row){
      this.countDiffe()
    },
    //计算盘点差异
    countDiffe(){
      this.form.diffeList=[]
      this.form.money=0
      this.form.storePanDetailList.map(item=>{
        if(item.realAmount !==item.storeAmount){
          item.realTotal=item.realAmount * (item.price || 0)
          item.diffeAmount=item.realAmount - item.storeAmount
          item.difference=item.diffeAmount* (item.price || 0)
          this.form.diffeList.push(item)
        }
        this.form.money+=item.realTotal
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open=true
      this.title='新增盘点'
    },
    cancelForm(){
      this.resetForm("form");
      this.open=false
    },
    submitForm(){
      this.$refs["form"].validate(valid => {
        if(valid){
          this.$confirm('请确认是否生成盘点单').then(res=> {
            getStoreDetailList(this.form).then(res => {
              saveNewStorePan(res.data).then(ret=>{
                this.$message.success('新增成功')
                this.cancelForm()
                this.getList()
              })
            })
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除编号为"' + row.id + '"的数据项？').then(()=>{
        deletePanInfo(row).then(res=>{
          this.$message.success("删除成功");
          this.getList();
        })
      })
    },
    handleDetail(row) {
      this.$router.push({
        path:'/store/calculate/detail/detail',
        query:{
          panNum:row.panNum,
          id:row.id
        }
      });
    },
    //提交盘点
    surePan(row){
      row.editFlag=true
    },
    cancel(row) {
      row.editFlag = false;
      this.getList();
    },
    submit(row) {
      if(!row.approvalUserId){
        this.$message.error('请选择审批人')
        return
      }
      row.approvalUser=this.approvalList.find(item=>item.userId===row.approvalUserId).nickName
      row.approvalState=1
      confirmStorePan(row).then(res=>{
        this.$message.success('提交成功')
        this.getList()
      }).catch(()=>{
        this.getList()
      })
    },
    //行导出
    rowExport(row){
      this.$router.push({
        path:'/jmreport/calculate',
        query:{
          id:'902846746292170752',
          rowId:row.panNum
        }
      })
    },
  }
};
</script>
